import { BaseListPage, http, IBaseListPageState, columnRenders, uaaApp, UdDrawer } from '@/lib'
import { downBlobFile } from '@/utils/methods'
import { Button, Upload, Icon, Modal, message, Select, TreeSelect } from 'antd'
import apis from '@/apis/CustomerManage'
import apiss from '@/apis'
import React from 'react'
import './index.scss'
import udMainStore from '@/store/UdMain'
import OperatingItemsDrawer from './OperatingItemsDrawer'

const { Option } = Select
const { TreeNode } = TreeSelect

const AddBtnAuth = 'user_domainandproduct_manager_insert'
const DetailBtnAuth = 'user_domainandproduct_manager_list'

interface IState extends IBaseListPageState {
  visible: boolean
  isLoading: boolean
  treeDataList: any[]
}

export default class AreaAndProducts extends BaseListPage<any, IState> {
  public brandList = udMainStore.brandList

  private TypeList: any[] = [
    {
      acctType: '1',
      name: '经销商',
    },
    {
      acctType: '2',
      name: '分销商',
    },
  ]

  constructor(props) {
    super(props)
    this.state = {
      visible: false,
      isLoading: false,
      title: '经销商销售区域与产品维护',
      rowKey: (record, index) => index + '',
      queryApi: params => {
        const agentType = 0
        return http.post(apis.CustomerList, { ...params, agentType })
      },
      conditions: [
        { id: 'agentName', label: '客户名称' },
        {
          id: 'brandCode',
          label: '品牌公司',
          render: (
            <Select
              allowClear={true}
              showSearch={true}
              optionFilterProp="children"
              onChange={value => {
                this.changeBrandCode(value)
              }}
            >
              {this.brandList.map(({ value, title }) => (
                <Option key={value} value={value}>
                  {title}
                </Option>
              ))}
            </Select>
          ),
        },
        {
          label: '所属组织',
          id: 'belongAreaCode',
          render: () => (
            <TreeSelect showSearch treeNodeFilterProp="title">
              {this.mapTree(this.state.treeDataList)}
            </TreeSelect>
          ),
        },
        {
          label: '客户类型',
          id: 'accoutType',
          render: () => (
            <Select placeholder="请选择客户类型">
              {this.TypeList.length > 0 &&
                this.TypeList.map(({ acctType, name }) => {
                  return (
                    <Option key={acctType} value={acctType}>
                      {name}
                    </Option>
                  )
                })}
            </Select>
          ),
        },
        { id: 'agentCode', label: '客户编码' },
      ],
      columns: [
        ['客户编码', 'agentCode', null, { minWidth: '100px' }],
        ['客户名称', 'agentName', null, { minWidth: '200px' }],
        ['销售组织', 'brandName', null, { minWidth: '200px' }],
        { dataIndex: 'agentType', title: '客户类型', minWidth: '80px', render: () => '经销商' },
        ['片区', 'belongAreaName', null, { minWidth: '120px' }],
        // ['创建时间', 'createdTime', null, { minWidth: '120px' }],
        // ['创建人', 'createdBy', null, { minWidth: '80px' }],
        // ['最近修改时间', 'updatedTime', null, { minWidth: '120px' }],
        // ['最近修改人', 'updatedBy', null, { minWidth: '80px' }],
        {
          title: '操作',
          fixedWidth: '180px',
          dataIndex: 'operate',
          fixed: 'right',
          render: columnRenders.operate([
            {
              title: '维护销售区域与产品',
              auth: AddBtnAuth,
              action: (text, row) => {
                this.handShowOperatingItemsModal(row)
                // props.history.push('/customer/areaproduts/add/' + row.id + '/' + row.agentName)
              },
            },
            {
              title: '查看详情',
              auth: DetailBtnAuth,
              action: (text, row) => {
                props.history.push('/customer/areaproduts/details/' + row.id + '/' + row.agentName)
              },
            },
          ]),
        },
      ],
      leftBtns: [
        () => (
          <Button
            onClick={() => {
              this.setState({ visible: true })
            }}
            type="primary"
          >
            导入
          </Button>
        ),
        () => (
          <Button
            onClick={() => {
              this.handleExport()
            }}
            type="primary"
          >
            导出
          </Button>
        ),
      ],
      tableProps: {
        scroll: { x: true },
        rowSelection: null,
      },
      treeDataList: [],
    }
  }

  private mapTree = (data: any[]) => {
    return data.map(item => {
      return (
        <TreeNode value={item.code} title={item.name} key={item.code}>
          {this.mapTree(item?.children || [])}
        </TreeNode>
      )
    })
  }
  private changeBrandCode = (value: any, callBack?: Function) => {
    this.filterForm.setFieldsValue({ prodBarcode: undefined, belongAreaCode: undefined }, () => {
      this.setState({ treeDataList: [] }, () => {
        Promise.allSettled([this.getAreaList(value)]).then((res: any) => {
          this.setState({
            treeDataList: res[0]?.value || [],
          })
        })
      })
    })
  }
  private getAreaList = (value: any) => {
    if (Object.is(value, undefined)) return []
    return http
      .get(apiss.getTreeByUser, {
        params: { organizationCode: value },
      })
      .then(res => {
        let data = res?.data?.children || []
        return data
      })
  }

  private handShowOperatingItemsModal = (record) => {
    UdDrawer.open({
      title: '维护销售区域与产品',
      width: '65%',
      content: <OperatingItemsDrawer record={record}  />,
      footer: null,
    })
  }

  private handleExport = () => {
    const agentType = 0
    const queryParams = this.getQueryParams() || {}
    this.downloadExcel(apis.AreaAndProductDown, { agentType, ...queryParams }, '经销商销售区域与产品维护列表')
    /* axios({
            url: (http.defaults.baseURL + apis.AreaAndProductDown),
            method: "GET",
            params: { agentType, ...queryParams },
            headers: {
                Authorization: uaaApp.getToken(),
                accountType: 0,
            },
            responseType: 'blob',
        }).then(async res => {
            const response: any = await blobToObject(res.data)
            if (!response.code) {
                downBlobFile(res.data, "经销商销售区域与产品维护列表")
            } else (
                udConfigProvider.http.errorHandler[response.code](response)
            )
        }).catch(async err => {
            const data = err.response.data
            const response: any = await blobToObject(data)
            udConfigProvider.http.errorTip({ message: '系统消息', description: response.msg })
        }) */
  }

  private downloadExcel = (url, params, fileName) => {
    http.get(url, { params, responseType: 'arraybuffer' }).then(res => {
      if (!res.data.code) {
        downBlobFile(res.data, fileName)
      }
    })
  }

  componentWillUnmount() {
    this.setState = (state, callback) => {
      return
    }
  }

  public componentDidMount() {
    super.componentDidMount()
    this.changeBrandCode(this.brandList[0].value)
  }

  render() {
    const props = {
      name: 'file',
      beforeUpload: (file, fileList) => {
        this.setState({ isLoading: true })

        let formData = new FormData()
        formData.append('file', file)
        http
          .post(
            apis.AreaAndProductImport +
              '?brandCode=' +
              JSON.parse(sessionStorage.getItem('UaaSysInfo'))?.profile?.brandCode,
            formData,
            {
              headers: { 'Content-Type': 'multipart/form-data' },
            }
          )
          .then((res: any) => {
            if (res.status === 200) {
              message.success('导入成功！')
              this.setState({ isLoading: false, visible: false })
              this.query()
            }
          })
          .catch(err => {
            this.setState({ isLoading: false })
          })
        return false
      },
      showUploadList: false,
    }
    return (
      <>
        {super.render()}
        <Modal
          title="导入"
          visible={this.state.visible}
          onCancel={() => {
            this.setState({ visible: false })
          }}
          onOk={() => {
            this.setState({ visible: false })
            this.query()
          }}
        >
          <div className="area-products-import-box">
            <p>第一步：下载模版</p>
            <Button
              onClick={() => {
                this.downloadExcel(apis.template, {}, '经销商销售区域与产品维护列表')
              }}
            >
              <Icon type="download" /> 下载模版
            </Button>
            <p>第二步：上传文件</p>
            <Upload {...props}>
              <Button>
                <Icon type={this.state.isLoading ? 'loading' : 'upload'} /> 上传文件
              </Button>
            </Upload>
          </div>
        </Modal>
      </>
    )
  }
}
